package usf.vend.a.bull.db;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class VendabullDBH extends SQLiteOpenHelper
{
	private static final String DB_PATH = "/data/data/usf.vend.a.bull/databases/";
	private static final String DB_NAME = "vendabull.db";
	private static int DB_VERSION = 1;
	private Context context;
	private boolean versionChecked = false;
	private boolean newVersionAvailable = false;
	//private static int newVersion;
	
	/*
	private static final String CREATE_COLLEGES_TABLE = "create table colleges("
			+ "_id integer primary key autoincrement"
			+ "college text not null"
			+ "lat text not null"
			+ "lng text not null)";
	private static final String CREATE_BUILDINGS_TABLE = "create table buildings("
			+ "_id integer primary key autoincrement"
			+ "college_id integer not null"
			+ "building text not null"
			+ "name text not null"
			+ "lat text not null"
			+ "lng text not null)";
	private static final String CREATE_MACHINES_TABLE = "create table machines("
			+ "_id integer primary key autoincrement"
			+ "building_id integer not null"
			+ "type text not null"
			+ "lat text not null"
			+ "lng text not null"
			+ "floor text not null)";	
			*/
	
	private SQLiteDatabase database;
	
	public VendabullDBH(Context context)
	{
		super(context, DB_NAME, null, DB_VERSION);
		this.context = context;
	}
	
	@Override
	public void onCreate(SQLiteDatabase database)
	{
		//preloaded database
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion)
	{
		//copyDatabase();
		newVersionAvailable = false;
		Log.d("VendabullDBH", "new version is " + newVersion);
	}
	
	public void createDataBase() throws IOException{
		 
    	boolean dbExist = checkDatabase();
 
    	if(dbExist)
    	{
    		//do nothing - database already exist
    	}
    	else
    	{ 
    		//By calling this method and empty database will be created into the default system path
               //of your application so we are gonna be able to overwrite that database with our database.
        	this.getReadableDatabase();
 
        	try
        	{
    			copyDatabase();
    		}
        	catch (IOException e)
        	{ 
        		throw new Error("Error copying database");
        	}
    	}
 
    }
	
	private boolean checkDatabase()
	{
		SQLiteDatabase exists = null;
		try
		{
			String path = DB_PATH + DB_NAME;
			exists = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
		}
		catch (SQLException e)
		{
			//database is not there
			Log.d("database", "database could not be opened");
		}
		
		if (exists != null)
		{
			exists.close();
			return true;
		}
		else
			return false;
	}
	
//	private void copyDatabase()
//	{
//		try
//		{
//	    	// Open your local db as the input stream
//			String dir = Environment.getExternalStorageDirectory() + "/download/";
//			
//			File db = new File(dir, DB_NAME);
//	    	FileInputStream myInput = new FileInputStream(db);
//	    	
//	    	// Path to the just created empty db
//	    	String outFileName = DB_PATH + DB_NAME;
//	    	// Open the empty db as the output stream
//	    	OutputStream myOutput = new FileOutputStream(outFileName);
//	 
//	    	// Transfer bytes from the inputfile to the outputfile
//	    	byte[] buffer = new byte[1024];
//	    	int length;
//	    	while ((length = myInput.read(buffer))>0){
//	    		myOutput.write(buffer, 0, length);
//	    	}
//	 
//	    	// Close the streams
//	    	myOutput.flush();
//	    	myOutput.close();
//	    	myInput.close();
//		}
//		catch (IOException ex)
//		{
//			Log.d("VendabullDBM", "copyDatabase() has failed");
//		}
//    }
	
	 private void copyDatabase() throws IOException
     {
     // Open your local db as the input stream
     InputStream myInput = context.getAssets().open(DB_NAME);
     // Path to the just created empty db
     String outFileName = DB_PATH + DB_NAME;
     // Open the empty db as the output stream
     OutputStream myOutput = new FileOutputStream(outFileName);

     // Transfer bytes from the inputfile to the outputfile
     byte[] buffer = new byte[1024];
     int length;
     while ((length = myInput.read(buffer))>0){
             myOutput.write(buffer, 0, length);
     }

     // Close the streams
     myOutput.flush();
     myOutput.close();
     myInput.close();
 }
 
    public SQLiteDatabase openDataBase() throws SQLException
    {
    	//Open the database
        String myPath = DB_PATH + DB_NAME;
    	database = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    	return database;
    }
    
    public void checkVersion()
	{
    	if (!versionChecked)
    	{
			try
			{
				URL url = new URL("http://rpobrien.myweb.usf.edu/Android/database/version.txt");
				HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
				urlCon.setRequestMethod("GET");
				urlCon.setDoOutput(true);
				urlCon.connect();
				
				String sdCard = Environment.getExternalStorageDirectory() + "/download/";
				String fileName = "db_version.txt";
				File file = new File(sdCard);
				file.mkdirs();
				
				
				File outputFile = new File(file, fileName);
				FileOutputStream fOStream = new FileOutputStream(outputFile);
				InputStream iStream = urlCon.getInputStream();
				
				byte[] buffer = new byte[256];
				int bufLength = 0;
				while ((bufLength = iStream.read(buffer)) != -1)
				{
					fOStream.write(buffer, 0, bufLength);
				}
				
				fOStream.flush();
				fOStream.close();
				iStream.close();
				
				StringBuilder versionStr = new StringBuilder();
				BufferedReader reader = new BufferedReader(new FileReader(outputFile));
				String line;
				while ((line = reader.readLine()) != null)
				{
					versionStr.append(line);
				}
				Log.d("DBUpdater", versionStr.toString());
				String[] str = versionStr.toString().split(":");
				int newVersion = Integer.parseInt(str[1].trim());
				Log.d("DBUpdater", "" + newVersion);
				
				if (newVersion > DB_VERSION)
				{
					newVersionAvailable = true;
					getNewDatabase(newVersion);
				}
			}
			catch (IOException ex)
			{
				Log.d("DBUpdater", "Could not check version");
			}
			versionChecked = true;
			
    	}
    }
    
    private void getNewDatabase(int newVersion)
    {
    	if (newVersionAvailable)
    	{
    		String sdCard = Environment.getExternalStorageDirectory() + "/download/";
			String fileName = "vendabull.db";
			try
			{
				URL url = new URL("http://rpobrien.myweb.usf.edu/Android/database/vendabull.db");
				HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
				urlCon.setRequestMethod("GET");
				urlCon.setDoOutput(true);
				urlCon.connect();
				
				File file = new File(sdCard);
				file.mkdirs();
				
				File outputFile = new File(file, fileName);
				FileOutputStream fOStream = new FileOutputStream(outputFile);
				InputStream iStream = urlCon.getInputStream();
				
				byte[] buffer = new byte[1024];
				int bufLength = 0;
				while ((bufLength = iStream.read(buffer)) != -1)
				{
					fOStream.write(buffer, 0, bufLength);
				}
				
				fOStream.flush();
				fOStream.close();
				iStream.close();
			}
			catch (IOException ex)
			{
				Log.d("DBUpdater", "Could not check version");
			}
			DB_VERSION = newVersion;
			Log.d("VendabullDBH", "changed DB_VERSION to " + newVersion);
    	}
    }
}
